<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AOC航务席位岗位风险隐患清单</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <style>
        :root {
            --primary: #1a73e8;
            --secondary: #4285f4;
            --accent: #f44336;
            --light: #f8f9fa;
            --dark: #202124;
            --success: #34a853;
            --warning: #fbbc05;
            --gray: #5f6368;
            --card-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            --sidebar-width: 250px;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: #f5f7fa;
            color: var(--dark);
            line-height: 1.6;
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: var(--sidebar-width);
            background: linear-gradient(180deg, #1a73e8, #4285f4);
            color: white;
            padding: 20px 0;
            box-shadow: var(--card-shadow);
            overflow-y: auto;
            position: fixed;
            height: 100vh;
            z-index: 100;
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 20px;
        }

        .sidebar-header h2 {
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .sidebar-header h2 i {
            font-size: 1.5rem;
        }

        .position-list {
            list-style: none;
        }

        .position-item {
            padding: 12px 20px;
            cursor: pointer;
            transition: all 0.3s;
            border-left: 4px solid transparent;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .position-item:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .position-item.active {
            background-color: rgba(255, 255, 255, 0.15);
            border-left-color: white;
        }

        .position-item i {
            width: 20px;
            text-align: center;
        }

        .position-count {
            margin-left: auto;
            background: rgba(255, 255, 255, 0.2);
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: bold;
        }

        .main-content {
            flex: 1;
            margin-left: var(--sidebar-width);
            padding: 20px;
            width: calc(100% - var(--sidebar-width));
        }

        header {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            margin-bottom: 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .logo i {
            font-size: 2.2rem;
            color: var(--primary);
        }

        .logo h1 {
            font-size: 1.8rem;
            font-weight: 600;
            color: var(--dark);
        }

        .header-info {
            display: flex;
            gap: 20px;
            align-items: center;
        }

        .help-text {
            font-size: 0.9rem;
            color: var(--gray);
        }

        .btn {
            background: var(--primary);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            font-size: 0.9rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn:hover {
            background: var(--secondary);
            transform: translateY(-2px);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .btn-outline {
            background: transparent;
            border: 1px solid var(--primary);
            color: var(--primary);
        }

        .btn-outline:hover {
            background: var(--primary);
            color: white;
        }

        .btn-success {
            background: var(--success);
        }

        .btn-success:hover {
            background: #2d9249;
        }

        .btn-warning {
            background: var(--warning);
            color: var(--dark);
        }

        .btn-warning:hover {
            background: #e6a800;
        }

        .loading {
            position: relative;
        }

        .loading:after {
            content: '';
            position: absolute;
            width: 16px;
            height: 16px;
            margin: auto;
            border: 2px solid transparent;
            border-top-color: #ffffff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin-bottom: 25px;
        }

        .stat-card {
            background: white;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            padding: 20px;
            text-align: center;
            transition: transform 0.3s;
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .stat-card i {
            font-size: 2rem;
            margin-bottom: 15px;
        }

        .stat-card h3 {
            font-size: 1.8rem;
            margin-bottom: 5px;
            color: var(--dark);
        }

        .stat-card p {
            color: var(--gray);
            font-size: 0.9rem;
        }

        .risk-low {
            color: var(--success);
        }

        .risk-medium {
            color: var(--warning);
        }

        .risk-high {
            color: var(--accent);
        }

        /* 重点风险源词云样式 */
        .risk-cloud-section {
            background: white;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            padding: 25px;
            margin-bottom: 30px;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #eee;
        }

        .section-header h2 {
            font-size: 1.5rem;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .section-header i {
            font-size: 1.8rem;
            color: var(--primary);
        }

        .risk-cloud-container {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 25px;
        }

        .position-cloud {
            background: linear-gradient(135deg, #f8f9ff, #ffffff);
            border-radius: 12px;
            padding: 20px;
            border: 1px solid #e8f0ff;
            transition: all 0.3s ease;
        }

        .position-cloud:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(26, 115, 232, 0.15);
            border-color: var(--primary);
        }

        .position-cloud h3 {
            font-size: 1.1rem;
            color: var(--primary);
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 1px solid #e8f0ff;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .cloud-words {
            display: flex;
            flex-direction: column;
            gap: 12px;
            min-height: 120px;
            padding: 10px 0;
        }

        .risk-word {
            padding: 12px 16px;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            line-height: 1.4;
            border-left: 4px solid;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            font-size: 0.95rem;
        }

        .risk-word.high-risk {
            background: linear-gradient(135deg, #ff4757, #ff6b7a);
            color: white;
            border-left-color: #ff1744;
            animation: pulse-glow 2s infinite;
        }

        .risk-word.medium-risk {
            background: linear-gradient(135deg, #ffa726, #ffb74d);
            color: white;
            border-left-color: #ff8f00;
            animation: pulse-glow 2s infinite;
        }

        .risk-word.low-risk {
            background: linear-gradient(135deg, #66bb6a, #81c784);
            color: white;
            border-left-color: #4caf50;
            animation: pulse-glow 2s infinite;
        }

        .risk-word.normal {
            background: linear-gradient(135deg, #78909c, #90a4ae);
            color: white;
            border-left-color: #607d8b;
            animation: pulse-glow 2s infinite;
        }

        .risk-word.purple-risk {
            background: linear-gradient(135deg, #9c27b0, #ba68c8);
            color: white;
            border-left-color: #7b1fa2;
            animation: pulse-glow 2s infinite;
        }

        .risk-word.blue-risk {
            background: linear-gradient(135deg, #2196f3, #64b5f6);
            color: white;
            border-left-color: #1976d2;
            animation: pulse-glow 2s infinite;
        }

        .risk-word.teal-risk {
            background: linear-gradient(135deg, #009688, #4db6ac);
            color: white;
            border-left-color: #00695c;
            animation: pulse-glow 2s infinite;
        }

        .risk-word.indigo-risk {
            background: linear-gradient(135deg, #3f51b5, #7986cb);
            color: white;
            border-left-color: #303f9f;
            animation: pulse-glow 2s infinite;
        }

        .risk-word.pink-risk {
            background: linear-gradient(135deg, #e91e63, #f06292);
            color: white;
            border-left-color: #c2185b;
            animation: pulse-glow 2s infinite;
        }

        .risk-word.cyan-risk {
            background: linear-gradient(135deg, #00bcd4, #4dd0e1);
            color: white;
            border-left-color: #0097a7;
            animation: pulse-glow 2s infinite;
        }

        .risk-word:hover {
            transform: translateX(5px) scale(1.02);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            z-index: 10;
        }

        .risk-word:before {
            content: '⚠ ';
            margin-right: 8px;
            font-size: 1.1em;
        }

        .risk-word.high-risk:before {
            content: '🔥';
        }

        .risk-word.medium-risk:before {
            content: '⚡';
        }

        .risk-word.low-risk:before {
            content: '🔋';
        }

        @keyframes pulse-glow {
            0% {
                box-shadow: 0 2px 8px rgba(255, 71, 87, 0.3), 0 0 0 0 rgba(255, 71, 87, 0.7);
            }
            70% {
                box-shadow: 0 2px 8px rgba(255, 71, 87, 0.3), 0 0 0 8px rgba(255, 71, 87, 0);
            }
            100% {
                box-shadow: 0 2px 8px rgba(255, 71, 87, 0.3), 0 0 0 0 rgba(255, 71, 87, 0);
            }
        }

        /* 数据表格样式 */
        .card {
            background: white;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            padding: 20px;
            transition: transform 0.3s;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .card-header h2 {
            font-size: 1.2rem;
            color: var(--dark);
        }

        .card-header i {
            font-size: 1.5rem;
            color: var(--primary);
        }

        .position-content {
            display: none;
        }

        .position-content.active {
            display: block;
        }

        .risk-table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: var(--card-shadow);
        }

        th,
        td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
            vertical-align: top;
        }

        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: var(--dark);
            position: sticky;
            top: 0;
        }

        tr:hover {
            background-color: #f1f8ff;
        }

        .risk-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .low {
            background-color: #e6f4ea;
            color: var(--success);
        }

        .medium {
            background-color: #fef7e0;
            color: var(--warning);
        }

        .high {
            background-color: #fce8e6;
            color: var(--accent);
        }

        .source-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
            background-color: #e8f0fe;
            color: var(--primary);
        }

        .source-danger {
            background-color: #fce8e6;
            color: var(--accent);
        }

        .source-warning {
            background-color: #fef7e0;
            color: var(--warning);
        }

        /* 分页样式 */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
            margin: 20px 0;
            padding: 20px;
            flex-wrap: wrap;
        }

        .pagination button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background: white;
            color: var(--dark);
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 14px;
            min-width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .pagination button:hover:not(:disabled):not([disabled]) {
            background: var(--primary);
            color: white;
            border-color: var(--primary);
            transform: translateY(-1px);
        }

        .pagination button:disabled,
        .pagination button[disabled] {
            opacity: 0.5;
            cursor: not-allowed;
            background: #f5f5f5;
            color: #999;
        }

        .pagination button.active {
            background: var(--primary);
            color: white;
            border-color: var(--primary);
            font-weight: bold;
        }

        .pagination .page-info {
            margin: 0 15px;
            font-size: 0.9rem;
            color: var(--gray);
            white-space: nowrap;
        }

        .pagination span {
            padding: 8px 4px;
            color: var(--gray);
        }

        /* 留言板样式 */
        .message-board {
            background: white;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            padding: 20px;
            margin-top: 30px;
        }

        .message-form {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group.full-width {
            grid-column: span 2;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: var(--dark);
        }

        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 1rem;
            transition: border-color 0.3s;
        }

        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
        }

        .form-group textarea {
            min-height: 120px;
            resize: vertical;
        }

        .message-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            grid-column: span 2;
        }

        .messages-list {
            border-top: 1px solid #eee;
            padding-top: 20px;
            max-height: 300px;
            overflow-y: auto;
        }

        .message-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
        }

        .message-item:last-child {
            border-bottom: none;
        }

        .message-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }

        .message-author {
            font-weight: 600;
            color: var(--primary);
        }

        .message-date {
            color: var(--gray);
            font-size: 0.85rem;
        }

        .message-content {
            color: var(--dark);
            line-height: 1.5;
        }

        .empty-message {
            text-align: center;
            color: var(--gray);
            padding: 20px;
        }

        /* 密码模态框样式 */
        .password-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1010;
            justify-content: center;
            align-items: center;
        }

        .password-modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 12px;
            width: 90%;
            max-width: 400px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
        }

        .password-modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .password-modal-header h2 {
            color: var(--primary);
        }

        .password-close {
            font-size: 1.5rem;
            cursor: pointer;
            color: var(--gray);
        }

        .password-form-group {
            margin-bottom: 20px;
        }

        .password-form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }

        .password-form-group input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 1rem;
        }

        .password-modal-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 12px;
            width: 90%;
            max-width: 600px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            max-height: 80vh;
            overflow-y: auto;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .modal-header h2 {
            color: var(--primary);
        }

        .close {
            font-size: 1.5rem;
            cursor: pointer;
            color: var(--gray);
        }

        footer {
            text-align: center;
            padding: 20px;
            color: var(--gray);
            font-size: 0.9rem;
            margin-top: 40px;
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            background-color: var(--success);
            color: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            display: none;
            z-index: 1001;
        }

        .notification.error {
            background-color: var(--accent);
        }

        @media (max-width: 1024px) {
            .stats {
                grid-template-columns: repeat(2, 1fr);
            }

            .risk-cloud-container {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 60px;
                overflow: visible;
            }

            .sidebar-header h2 span,
            .position-item span {
                display: none;
            }

            .position-item {
                text-align: center;
                padding: 15px 0;
            }

            .position-item i {
                margin-right: 0;
                font-size: 1.2rem;
            }

            .main-content {
                margin-left: 60px;
                width: calc(100% - 60px);
            }

            header {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }

            .header-info {
                flex-direction: column;
                gap: 10px;
            }

            .stats {
                grid-template-columns: 1fr;
            }

            .message-form {
                grid-template-columns: 1fr;
            }

            .form-group.full-width {
                grid-column: span 1;
            }

            .message-actions {
                grid-column: span 1;
            }

            /* 移动端分页样式优化 */
            .pagination {
                gap: 4px;
                padding: 15px 10px;
            }

            .pagination button {
                padding: 6px 8px;
                font-size: 12px;
                min-width: 32px;
                height: 32px;
            }

            .pagination .page-info {
                font-size: 0.8rem;
                margin: 0 8px;
            }

            /* 表格横向滚动优化 */
            .risk-table-container {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }

            table {
                min-width: 600px;
            }

            th, td {
                padding: 10px 8px;
                font-size: 0.9rem;
            }
        }
    </style>
</head>

<body>
    <div class="sidebar">
        <div class="sidebar-header">
            <h2><i class="fas fa-plane"></i> <span>岗位选择</span></h2>
        </div>
        <ul class="position-list" id="position-list">
            <li class="position-item active" data-position="dispatch">
                <i class="fas fa-paper-plane"></i> 
                <span>签派放行席</span>
                <span class="position-count" id="count-dispatch">0</span>
            </li>
            <li class="position-item" data-position="plan-control">
                <i class="fas fa-clipboard-list"></i> 
                <span>计划控制席</span>
                <span class="position-count" id="count-plan-control">0</span>
            </li>
            <li class="position-item" data-position="dispatch-support">
                <i class="fas fa-hands-helping"></i> 
                <span>签派支援席</span>
                <span class="position-count" id="count-dispatch-support">0</span>
            </li>
            <li class="position-item" data-position="flight-plan">
                <i class="fas fa-route"></i> 
                <span>航班计划席</span>
                <span class="position-count" id="count-flight-plan">0</span>
            </li>
            <li class="position-item" data-position="assistant-dispatch">
                <i class="fas fa-user-friends"></i> 
                <span>助理签派席</span>
                <span class="position-count" id="count-assistant-dispatch">0</span>
            </li>
        </ul>
    </div>

    <div class="main-content">
        <header>
            <div class="logo">
                <i class="fas fa-plane-departure"></i>
                <div>
                    <h1>AOC航务席位风险隐患清单</h1>
                    <p class="help-text">当前查看: <span id="current-position">签派放行席</span> | 最后更新: <span
                            id="update-date">2023-11-05</span></p>
                </div>
            </div>
            <div class="header-info">
                <button class="btn" id="upload-btn">
                    <i class="fas fa-upload"></i> 导入Excel数据
                </button>
                <button class="btn btn-outline" id="sync-btn">
                    <i class="fas fa-sync-alt"></i> 同步数据
                </button>
                <button class="btn btn-outline" id="clear-data-btn">
                    <i class="fas fa-trash"></i> 清除数据
                </button>
                <button class="btn btn-outline" id="help-btn">
                    <i class="fas fa-question-circle"></i> 使用帮助
                </button>
            </div>
        </header>

        <div class="stats">
            <div class="stat-card">
                <i class="fas fa-exclamation-triangle risk-medium"></i>
                <h3 id="total-risks">0</h3>
                <p>风险总数</p>
            </div>
            <div class="stat-card">
                <i class="fas fa-check-circle risk-low"></i>
                <h3 id="managed-risks">0</h3>
                <p>已管控风险</p>
            </div>
            <div class="stat-card">
                <i class="fas fa-clipboard-list risk-medium"></i>
                <h3 id="position-count">5</h3>
                <p>岗位数量</p>
            </div>
        </div>

        <!-- 重点风险源展示区域 -->
        <div class="risk-cloud-section">
            <div class="section-header">
                <h2><i class="fas fa-exclamation-triangle"></i> 重点风险源</h2>
                <p class="help-text">各岗位重点风险隐患汇总</p>
            </div>
            <div class="risk-cloud-container" id="risk-cloud-container">
                <!-- 重点风险内容将由JavaScript动态生成 -->
            </div>
        </div>

        <!-- 数据表格内容区域 -->
        <div id="data-content-area">
            <!-- 各岗位内容将由JavaScript动态生成 -->
        </div>

        <!-- 留言板 -->
        <div class="message-board">
            <div class="card-header">
                <h2>风险留言板</h2>
                <i class="fas fa-comments"></i>
            </div>

            <form id="message-form" class="message-form">
                <div class="form-group">
                    <label for="author-name">填写人姓名</label>
                    <input type="text" id="author-name" placeholder="请输入您的姓名" required>
                </div>

                <div class="form-group">
                    <label for="author-position">岗位</label>
                    <select id="author-position" required>
                        <option value="">请选择岗位</option>
                        <option value="签派放行席">签派放行席</option>
                        <option value="计划控制席">计划控制席</option>
                        <option value="签派支援席">签派支援席</option>
                        <option value="航班计划席">航班计划席</option>
                        <option value="助理签派席">助理签派席</option>
                    </select>
                </div>

                <div class="form-group full-width">
                    <label for="message-content">风险/内容</label>
                    <textarea id="message-content" placeholder="请输入风险描述或留言内容..." required></textarea>
                </div>

                <div class="message-actions">
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-paper-plane"></i> 提交留言
                    </button>
                    <button type="button" id="download-messages" class="btn">
                        <i class="fas fa-download"></i> 下载留言
                    </button>
                    <button type="button" id="clear-messages" class="btn btn-warning">
                        <i class="fas fa-trash"></i> 清零留言
                    </button>
                </div>
            </form>

            <div class="messages-list" id="messages-list">
                <div class="empty-message" id="empty-message">
                    <i class="fas fa-comment-slash" style="font-size: 2rem; margin-bottom: 10px;"></i>
                    <p>暂无留言，快来发表第一条风险留言吧！</p>
                </div>
            </div>
        </div>

        <footer>
            <p>AOC航务席位岗位风险隐患清单 &copy; 2023 | 数据仅用于演示目的</p>
        </footer>
    </div>

    <!-- 密码验证模态框 -->
    <div id="password-modal" class="password-modal">
        <div class="password-modal-content">
            <div class="password-modal-header">
                <h2>验证管理员身份</h2>
                <span class="password-close">&times;</span>
            </div>
            <p>请输入密码以清空留言内容：</p>
            <div class="password-form-group">
                <input type="password" id="password-input" placeholder="请输入密码">
            </div>
            <div class="password-modal-actions">
                <button type="button" class="btn btn-outline" id="password-cancel">取消</button>
                <button type="button" class="btn" id="password-confirm">确认</button>
            </div>
        </div>
    </div>

    <!-- 文件上传模态框 -->
    <div id="upload-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>上传Excel数据文件</h2>
                <span class="close">&times;</span>
            </div>
            <p>请选择包含民航风险数据的Excel文件：</p>
            <input type="file" id="file-input" accept=".xlsx, .xls" style="margin: 20px 0;">
            <div id="file-info"></div>
            <p class="help-text">支持格式: .xlsx, .xls | 文件大小限制: 10MB</p>
        </div>
    </div>

    <!-- 帮助模态框 -->
    <div id="help-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>使用帮助</h2>
                <span class="close">&times;</span>
            </div>
            <h3>数据格式要求</h3>
            <p>Excel文件需要包含以下工作表：</p>
            <ul style="margin: 15px 0 15px 20px;">
                <li><strong>常规岗位表</strong>：签派放行席、计划控制席、签派支援席、航班计划席、助理签派席</li>
                <li><strong>重点风险表</strong>：名为"重点风险"的工作表，A列为岗位名称，B列起为重点风险1-10</li>
            </ul>
            <p>常规岗位表格式：A列(风险隐患来源)、B列(风险/安全隐患)、C列(管控措施)、D列(危险源/隐患编号)</p>
            
            <h3>操作指导</h3>
            <p>1. 点击"导入Excel数据"按钮上传文件</p>
            <p>2. 使用左侧菜单切换不同岗位的风险数据</p>
            <p>3. 查看统计数据和重点危险源分析（五颜六色显示）</p>
            <p>4. 使用分页功能浏览大量数据（每页最多10条）</p>
            <p>5. 点击"清除数据"按钮可以清空所有保存的数据</p>
            
            <h3>共享功能</h3>
            <p><strong>📊 数据共享：</strong>管理员导入的数据会自动保存到服务器，所有访问者都能看到</p>
            <p><strong>🔄 数据同步：</strong>点击"同步数据"按钮获取最新的共享数据</p>
            <p><strong>💬 留言共享：</strong>所有留言都会实时保存到服务器，其他用户可以看到</p>
            <p><strong>🗑️ 数据管理：</strong>只有管理员可以清除共享数据和留言（需要密码：123456）</p>
            
            <h3>留言板功能</h3>
            <p>1. 填写姓名和选择岗位后，输入风险内容提交留言</p>
            <p>2. 点击"下载留言"可以将所有留言导出为文本文件</p>
            <p>3. 点击"清零留言"需要输入密码(123456)才能清空所有留言内容</p>
        </div>
    </div>

    <!-- 通知 -->
    <div id="notification" class="notification"></div>

    <script>
        // 全局数据存储
        let riskData = {};
        let keyRisksData = {}; // 新增：存储重点风险数据
        let currentPositionData = [];
        let currentPage = 1;
        const itemsPerPage = 10;

        // 配置服务器API地址（需要根据实际情况修改）
        const API_BASE_URL = '/api'; // 或者使用绝对URL如 'https://yourdomain.com/api'

        // 岗位映射表
        const positionMapping = {
            '签派放行席': 'dispatch',
            '计划控制席': 'plan-control',
            '签派支援席': 'dispatch-support',
            '航班计划席': 'flight-plan',
            '助理签派席': 'assistant-dispatch'
        };

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function () {
            // 首先尝试从服务器加载数据
            loadDataFromServer()
                .then(hasLoadedData => {
                    // 如果没有加载到数据，则加载示例数据
                    if (!hasLoadedData) {
                        loadSampleData();
                    }
                })
                .catch(error => {
                    console.error('从服务器加载数据失败:', error);
                    // 回退到本地存储
                    const hasLocalData = loadDataFromStorage();
                    if (!hasLocalData) {
                        loadSampleData();
                    }
                });

            // 初始化留言板
            initMessageBoard();

            // 岗位切换
            const positionItems = document.querySelectorAll('.position-item');
            const currentPositionElement = document.getElementById('current-position');

            positionItems.forEach(item => {
                item.addEventListener('click', function () {
                    const position = this.getAttribute('data-position');

                    // 更新激活状态
                    positionItems.forEach(i => i.classList.remove('active'));
                    this.classList.add('active');

                    // 更新当前查看岗位
                    currentPositionElement.textContent = this.querySelector('span').textContent;

                    // 切换数据内容
                    switchPositionContent(position);
                });
            });

            // 重点风险点击事件
            document.addEventListener('click', function(e) {
                if (e.target.classList.contains('risk-word')) {
                    const title = e.target.getAttribute('title') || e.target.textContent;
                    showNotification(`重点风险: ${title}`);
                }
            });

            // 模态框控制
            const uploadModal = document.getElementById('upload-modal');
            const helpModal = document.getElementById('help-modal');
            const passwordModal = document.getElementById('password-modal');
            const uploadBtn = document.getElementById('upload-btn');
            const syncBtn = document.getElementById('sync-btn');
            const clearDataBtn = document.getElementById('clear-data-btn');
            const helpBtn = document.getElementById('help-btn');
            const closeButtons = document.querySelectorAll('.close');
            const passwordClose = document.querySelector('.password-close');
            const passwordCancel = document.getElementById('password-cancel');

            uploadBtn.addEventListener('click', function () {
                uploadModal.style.display = 'flex';
            });

            syncBtn.addEventListener('click', async function () {
                this.classList.add('loading');
                this.disabled = true;
                try {
                    await loadDataFromServer();
                    showNotification('数据同步成功！');
                } catch (error) {
                    showNotification('数据同步失败：' + error.message, true);
                } finally {
                    this.classList.remove('loading');
                    this.disabled = false;
                }
            });

            clearDataBtn.addEventListener('click', function () {
                if (confirm('确定要清除所有保存的数据吗？此操作不可恢复。')) {
                    clearAllData();
                }
            });

            helpBtn.addEventListener('click', function () {
                helpModal.style.display = 'flex';
            });

            // 关闭按钮事件
            closeButtons.forEach(button => {
                button.addEventListener('click', function () {
                    uploadModal.style.display = 'none';
                    helpModal.style.display = 'none';
                });
            });

            // 密码模态框关闭事件
            passwordClose.addEventListener('click', function () {
                passwordModal.style.display = 'none';
            });

            passwordCancel.addEventListener('click', function () {
                passwordModal.style.display = 'none';
            });

            window.addEventListener('click', function (event) {
                if (event.target == uploadModal) {
                    uploadModal.style.display = 'none';
                }
                if (event.target == helpModal) {
                    helpModal.style.display = 'none';
                }
                if (event.target == passwordModal) {
                    passwordModal.style.display = 'none';
                }
            });

            // 文件上传处理
            const fileInput = document.getElementById('file-input');
            const fileInfo = document.getElementById('file-info');

            fileInput.addEventListener('change', () => {
                if (fileInput.files.length) {
                    handleFileUpload(fileInput.files[0]);
                }
            });
        });

        // 从服务器加载数据
        async function loadDataFromServer() {
            try {
                const response = await fetch(`${API_BASE_URL}/data`);
                if (!response.ok) {
                    if (response.status === 404) {
                        // 没有数据文件，这是正常的
                        console.log('服务器上没有数据文件');
                        return false;
                    }
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                
                if (data.riskData || data.keyRisksData) {
                    // 恢复数据
                    riskData = data.riskData || {};
                    keyRisksData = data.keyRisksData || {};
                    
                    // 检查是否有有效数据
                    const hasRiskData = Object.keys(riskData).some(pos => riskData[pos] && riskData[pos].data && riskData[pos].data.length > 0);
                    const hasKeyRiskData = Object.keys(keyRisksData).length > 0;
                    
                    if (hasRiskData || hasKeyRiskData) {
                        // 更新界面
                        updateStatistics();
                        updatePositionCounts();
                        generateRiskClouds();
                        
                        // 设置默认显示第一个有数据的岗位
                        const firstPosition = Object.keys(riskData).find(pos => riskData[pos] && riskData[pos].data && riskData[pos].data.length > 0);
                        if (firstPosition) {
                            const firstPositionKey = positionMapping[firstPosition];
                            if (firstPositionKey) {
                                // 更新侧边栏激活状态
                                document.querySelectorAll('.position-item').forEach(item => item.classList.remove('active'));
                                const firstItem = document.querySelector(`[data-position="${firstPositionKey}"]`);
                                if (firstItem) {
                                    firstItem.classList.add('active');
                                    document.getElementById('current-position').textContent = firstPosition;
                                }
                                switchPositionContent(firstPositionKey);
                            }
                        }
                        
                        // 更新最后修改日期
                        if (data.updateDate) {
                            document.getElementById('update-date').textContent = data.updateDate;
                        }
                        
                        console.log('已从服务器加载数据');
                        showNotification('已加载服务器上的共享数据');
                        return true;
                    }
                }
            } catch (error) {
                console.error('从服务器加载数据失败:', error);
                throw error;
            }
            return false;
        }

        // 保存数据到服务器
        async function saveDataToServer() {
            try {
                const dataToSave = {
                    riskData: riskData,
                    keyRisksData: keyRisksData,
                    timestamp: new Date().getTime(),
                    updateDate: new Date().toLocaleDateString()
                };
                
                const response = await fetch(`${API_BASE_URL}/data`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(dataToSave)
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                console.log('数据已保存到服务器');
                return true;
            } catch (error) {
                console.error('保存数据到服务器失败:', error);
                throw error;
            }
        }

        // 从服务器加载留言
        async function loadMessagesFromServer() {
            try {
                const response = await fetch(`${API_BASE_URL}/messages`);
                if (!response.ok) {
                    if (response.status === 404) {
                        return [];
                    }
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const messages = await response.json();
                return messages || [];
            } catch (error) {
                console.error('从服务器加载留言失败:', error);
                return [];
            }
        }

        // 保存留言到服务器
        async function saveMessageToServer(message) {
            try {
                const response = await fetch(`${API_BASE_URL}/messages`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(message)
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                return true;
            } catch (error) {
                console.error('保存留言到服务器失败:', error);
                throw error;
            }
        }

        // 从服务器清除留言
        async function clearMessagesOnServer() {
            try {
                const response = await fetch(`${API_BASE_URL}/messages`, {
                    method: 'DELETE'
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                return true;
            } catch (error) {
                console.error('从服务器清除留言失败:', error);
                throw error;
            }
        }

        // 文件上传处理
        async function handleFileUpload(file) {
            if (file && (file.name.endsWith('.xlsx') || file.name.endsWith('.xls'))) {
                if (file.size > 10 * 1024 * 1024) {
                    document.getElementById('file-info').innerHTML = '<p style="color: red;">文件大小不能超过10MB</p>';
                    return;
                }

                document.getElementById('file-info').innerHTML = `<p>已选择文件: <strong>${file.name}</strong> (${(file.size / 1024).toFixed(2)} KB)</p>`;

                // 解析Excel文件
                const reader = new FileReader();
                reader.onload = async function (e) {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });
                    await processExcelData(workbook);
                };
                reader.readAsArrayBuffer(file);

                showNotification('数据上传成功！正在解析数据...');

                // 3秒后关闭模态框
                setTimeout(() => {
                    document.getElementById('upload-modal').style.display = 'none';
                }, 3000);
            } else {
                document.getElementById('file-info').innerHTML = '<p style="color: red;">请选择有效的Excel文件 (.xlsx 或 .xls)</p>';
            }
        }

        // 处理Excel数据
        async function processExcelData(workbook) {
            const allSheetsData = {};
            let totalRisks = 0;

            // 处理常规岗位数据
            workbook.SheetNames.forEach(sheetName => {
                if (sheetName === '重点风险') return; // 跳过重点风险sheet，单独处理
                
                const worksheet = workbook.Sheets[sheetName];
                const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

                // 去掉表头，只保留数据行
                const dataRows = jsonData.slice(1).filter(row => {
                    return row && row[0] && row[0].toString().trim() !== '';
                });

                allSheetsData[sheetName] = {
                    headers: jsonData[0] || [],
                    data: dataRows
                };

                totalRisks += dataRows.length;
            });

            // 处理重点风险数据
            if (workbook.SheetNames.includes('重点风险')) {
                processKeyRisksData(workbook.Sheets['重点风险']);
            }

            // 存储数据
            riskData = allSheetsData;

            try {
                // 保存数据到服务器
                await saveDataToServer();
                showNotification('数据已保存到服务器，其他用户可以看到更新！');
            } catch (error) {
                // 如果服务器保存失败，回退到本地存储
                saveDataToStorage();
                showNotification('数据已保存到本地（服务器保存失败）', true);
            }

            // 更新界面
            updateStatistics();
            updatePositionCounts();
            generateRiskClouds();
            
            // 设置默认显示第一个有数据的岗位
            const firstPosition = Object.keys(riskData).find(pos => riskData[pos].data.length > 0);
            if (firstPosition) {
                const firstPositionKey = positionMapping[firstPosition];
                if (firstPositionKey) {
                    // 更新侧边栏激活状态
                    document.querySelectorAll('.position-item').forEach(item => item.classList.remove('active'));
                    const firstItem = document.querySelector(`[data-position="${firstPositionKey}"]`);
                    if (firstItem) {
                        firstItem.classList.add('active');
                        document.getElementById('current-position').textContent = firstPosition;
                    }
                    switchPositionContent(firstPositionKey);
                }
            }

            // 更新最后修改日期
            document.getElementById('update-date').textContent = new Date().toLocaleDateString();

            showNotification('数据解析完成！页面已更新并保存。');
        }

        // 保存数据到本地存储（备用方案）
        function saveDataToStorage() {
            try {
                const dataToSave = {
                    riskData: riskData,
                    keyRisksData: keyRisksData,
                    timestamp: new Date().getTime(),
                    updateDate: new Date().toLocaleDateString()
                };
                localStorage.setItem('aoc_risk_data', JSON.stringify(dataToSave));
                console.log('数据已保存到本地存储');
            } catch (error) {
                console.error('保存数据到本地存储失败:', error);
                showNotification('数据保存失败，请检查浏览器存储空间', true);
            }
        }

        // 从本地存储加载数据（备用方案）
        function loadDataFromStorage() {
            try {
                const savedData = localStorage.getItem('aoc_risk_data');
                if (savedData) {
                    const parsedData = JSON.parse(savedData);
                    
                    // 恢复数据
                    riskData = parsedData.riskData || {};
                    keyRisksData = parsedData.keyRisksData || {};
                    
                    // 检查是否有有效数据
                    const hasRiskData = Object.keys(riskData).some(pos => riskData[pos] && riskData[pos].data && riskData[pos].data.length > 0);
                    const hasKeyRiskData = Object.keys(keyRisksData).length > 0;
                    
                    if (hasRiskData || hasKeyRiskData) {
                        // 更新界面
                        updateStatistics();
                        updatePositionCounts();
                        generateRiskClouds();
                        
                        // 设置默认显示第一个有数据的岗位
                        const firstPosition = Object.keys(riskData).find(pos => riskData[pos] && riskData[pos].data && riskData[pos].data.length > 0);
                        if (firstPosition) {
                            const firstPositionKey = positionMapping[firstPosition];
                            if (firstPositionKey) {
                                // 更新侧边栏激活状态
                                document.querySelectorAll('.position-item').forEach(item => item.classList.remove('active'));
                                const firstItem = document.querySelector(`[data-position="${firstPositionKey}"]`);
                                if (firstItem) {
                                    firstItem.classList.add('active');
                                    document.getElementById('current-position').textContent = firstPosition;
                                }
                                switchPositionContent(firstPositionKey);
                            }
                        }
                        
                        // 更新最后修改日期
                        if (parsedData.updateDate) {
                            document.getElementById('update-date').textContent = parsedData.updateDate;
                        }
                        
                        console.log('已从本地存储加载数据');
                        showNotification('已加载上次保存的本地数据');
                        return true;
                    }
                }
            } catch (error) {
                console.error('从本地存储加载数据失败:', error);
                // 清除无效数据
                localStorage.removeItem('aoc_risk_data');
            }
            return false;
        }

        // 清除所有数据
        async function clearAllData() {
            try {
                // 尝试清除服务器数据
                const serverResponse = await fetch(`${API_BASE_URL}/data`, {
                    method: 'DELETE'
                });
                
                if (serverResponse.ok) {
                    showNotification('服务器数据已清除');
                } else {
                    showNotification('清除服务器数据失败', true);
                }
            } catch (error) {
                console.error('清除服务器数据失败:', error);
            }
            
            try {
                // 清除本地数据
                localStorage.removeItem('aoc_risk_data');
                // 重置数据
                riskData = {};
                keyRisksData = {};
                // 重新加载示例数据
                loadSampleData();
                showNotification('本地数据已清除');
            } catch (error) {
                console.error('清除本地数据失败:', error);
            }
        }

        // 处理重点风险数据
        function processKeyRisksData(worksheet) {
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
            const dataRows = jsonData.slice(1); // 跳过表头

            keyRisksData = {};
            const colorLevels = [
                'high-risk', 'medium-risk', 'low-risk', 'normal',
                'purple-risk', 'blue-risk', 'teal-risk', 'indigo-risk',
                'pink-risk', 'cyan-risk'
            ];

            dataRows.forEach(row => {
                if (row && row[0]) { // 第一列是岗位名称
                    const position = row[0];
                    const risks = [];
                    
                    // 从第二列开始是重点风险内容
                    for (let i = 1; i < row.length; i++) {
                        if (row[i] && row[i].toString().trim() !== '') {
                            risks.push({
                                title: `重点风险${i}`,
                                content: row[i].toString().trim(),
                                level: colorLevels[Math.floor(Math.random() * colorLevels.length)] // 随机分配颜色
                            });
                        }
                    }
                    
                    keyRisksData[position] = risks;
                }
            });

            console.log('重点风险数据处理完成:', keyRisksData);
        }

        // 更新统计数据
        function updateStatistics() {
            let totalRisks = 0;
            let managedRisks = 0;

            Object.values(riskData).forEach(positionData => {
                totalRisks += positionData.data.length;
                
                positionData.data.forEach(row => {
                    if (row[2] && row[2].trim() !== '') { // 有管控措施
                        managedRisks++;
                    }
                });
            });

            document.getElementById('total-risks').textContent = totalRisks;
            document.getElementById('managed-risks').textContent = managedRisks;
        }

        // 更新岗位计数
        function updatePositionCounts() {
            Object.keys(positionMapping).forEach(positionName => {
                const positionKey = positionMapping[positionName];
                const countElement = document.getElementById(`count-${positionKey}`);
                if (countElement && riskData[positionName]) {
                    countElement.textContent = riskData[positionName].data.length;
                }
            });
        }

        // 生成重点风险显示
        function generateRiskClouds() {
            const cloudContainer = document.getElementById('risk-cloud-container');
            cloudContainer.innerHTML = '';

            // 如果有重点风险数据，优先使用重点风险数据
            if (Object.keys(keyRisksData).length > 0) {
                generateKeyRisksDisplay();
                return;
            }

            // 回退到原有的词云逻辑（当没有重点风险数据时）
            Object.keys(positionMapping).forEach(positionName => {
                const positionKey = positionMapping[positionName];
                const positionData = riskData[positionName];
                
                if (!positionData || positionData.data.length === 0) return;

                const cloudDiv = document.createElement('div');
                cloudDiv.className = 'position-cloud';

                const icons = {
                    'dispatch': 'fas fa-paper-plane',
                    'plan-control': 'fas fa-clipboard-list',
                    'dispatch-support': 'fas fa-hands-helping',
                    'flight-plan': 'fas fa-route',
                    'assistant-dispatch': 'fas fa-user-friends'
                };

                const title = document.createElement('h3');
                title.innerHTML = `<i class="${icons[positionKey]}"></i> ${positionName}`;

                const wordsDiv = document.createElement('div');
                wordsDiv.className = 'cloud-words';

                // 提取关键词并生成词云
                const keywords = extractKeywords(positionData.data);
                keywords.forEach(keyword => {
                    const wordSpan = document.createElement('span');
                    wordSpan.className = `risk-word ${keyword.level}`;
                    wordSpan.textContent = keyword.word;
                    wordSpan.title = keyword.description;
                    wordsDiv.appendChild(wordSpan);
                });

                cloudDiv.appendChild(title);
                cloudDiv.appendChild(wordsDiv);
                cloudContainer.appendChild(cloudDiv);
            });
        }

        // 生成重点风险显示
        function generateKeyRisksDisplay() {
            const cloudContainer = document.getElementById('risk-cloud-container');
            cloudContainer.innerHTML = '';

            Object.keys(positionMapping).forEach(positionName => {
                const positionKey = positionMapping[positionName];
                const risks = keyRisksData[positionName] || [];

                const cloudDiv = document.createElement('div');
                cloudDiv.className = 'position-cloud';

                const icons = {
                    'dispatch': 'fas fa-paper-plane',
                    'plan-control': 'fas fa-clipboard-list',
                    'dispatch-support': 'fas fa-hands-helping',
                    'flight-plan': 'fas fa-route',
                    'assistant-dispatch': 'fas fa-user-friends'
                };

                const title = document.createElement('h3');
                title.innerHTML = `<i class="${icons[positionKey]}"></i> ${positionName}`;

                const risksDiv = document.createElement('div');
                risksDiv.className = 'cloud-words';

                if (risks.length === 0) {
                    risksDiv.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无重点风险数据</div>';
                } else {
                    risks.forEach(risk => {
                        const riskSpan = document.createElement('span');
                        riskSpan.className = `risk-word ${risk.level}`;
                        riskSpan.textContent = risk.content;
                        riskSpan.title = `${risk.title}: ${risk.content}`;
                        risksDiv.appendChild(riskSpan);
                    });
                }

                cloudDiv.appendChild(title);
                cloudDiv.appendChild(risksDiv);
                cloudContainer.appendChild(cloudDiv);
            });
        }

        // 提取关键词
        function extractKeywords(data) {
            const keywords = [];
            const wordMap = new Map();

            data.forEach(row => {
                const riskDesc = row[1] || '';
                const source = row[0] || '';
                
                // 提取一些关键词
                const words = riskDesc.match(/[\u4e00-\u9fa5]{2,8}/g) || [];
                
                words.forEach(word => {
                    if (word.length >= 2 && word.length <= 6) {
                        if (!wordMap.has(word)) {
                            wordMap.set(word, {
                                count: 1,
                                sources: [source],
                                descriptions: [riskDesc.substring(0, 50)]
                            });
                        } else {
                            const existing = wordMap.get(word);
                            existing.count++;
                            existing.sources.push(source);
                            existing.descriptions.push(riskDesc.substring(0, 50));
                        }
                    }
                });
            });

            // 转换为关键词数组并分级
            wordMap.forEach((info, word) => {
                let level = 'normal';
                if (info.count >= 3 || word.includes('故障') || word.includes('超时')) {
                    level = 'high-risk';
                } else if (info.count >= 2 || word.includes('风险') || word.includes('管控')) {
                    level = 'medium-risk';
                } else if (word.includes('安全') || word.includes('检查')) {
                    level = 'low-risk';
                }

                keywords.push({
                    word: word,
                    level: level,
                    description: `出现${info.count}次: ${info.descriptions[0]}...`
                });
            });

            // 限制显示数量
            return keywords.slice(0, 8);
        }

        // 切换岗位内容
        function switchPositionContent(positionKey) {
            const positionName = Object.keys(positionMapping).find(key => positionMapping[key] === positionKey);
            const positionData = riskData[positionName];

            // 重置到第一页
            currentPage = 1;

            if (!positionData || positionData.data.length === 0) {
                displayEmptyContent(positionName);
                return;
            }

            currentPositionData = positionData.data;
            displayPositionData(positionName, positionData);
        }

        // 显示岗位数据
        function displayPositionData(positionName, positionData) {
            const contentArea = document.getElementById('data-content-area');
            
            const startIndex = (currentPage - 1) * itemsPerPage;
            const endIndex = startIndex + itemsPerPage;
            const pageData = positionData.data.slice(startIndex, endIndex);

            contentArea.innerHTML = `
                <div class="card">
                    <div class="card-header">
                        <h2>${positionName} - 风险数据 (第${currentPage}页，共${Math.ceil(positionData.data.length / itemsPerPage)}页)</h2>
                        <i class="fas fa-table"></i>
                    </div>
                    <div class="risk-table-container">
                        <table>
                            <thead>
                                <tr>
                                    <th style="width: 15%;">风险来源</th>
                                    <th style="width: 35%;">风险描述</th>
                                    <th style="width: 40%;">管控措施</th>
                                    <th style="width: 10%;">隐患编号</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${pageData.map(row => `
                                    <tr>
                                        <td><span class="source-badge ${getSourceClass(row[0])}">${row[0] || 'N/A'}</span></td>
                                        <td>${row[1] || 'N/A'}</td>
                                        <td>${row[2] || 'N/A'}</td>
                                        <td>${row[3] || '/'}</td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                    ${generatePagination(positionData.data.length)}
                </div>
            `;

            // 延迟绑定分页事件，确保DOM已渲染
            setTimeout(() => {
                bindPaginationEvents(positionName, positionData);
            }, 0);
        }

        // 获取来源样式类
        function getSourceClass(source) {
            if (!source) return '';
            if (source.includes('危险源库')) return 'source-danger';
            if (source.includes('次日风险')) return 'source-warning';
            return '';
        }

        // 生成分页控件
        function generatePagination(totalItems) {
            const totalPages = Math.ceil(totalItems / itemsPerPage);
            if (totalPages <= 1) return '';

            let paginationHTML = '<div class="pagination">';
            
            // 上一页
            const prevDisabled = currentPage === 1 ? 'disabled' : '';
            paginationHTML += `<button ${prevDisabled} data-page="${currentPage - 1}" title="上一页">
                <i class="fas fa-chevron-left"></i>
            </button>`;

            // 页码按钮
            let startPage = Math.max(1, currentPage - 2);
            let endPage = Math.min(totalPages, currentPage + 2);

            // 确保显示5个页码（如果可能）
            if (endPage - startPage < 4) {
                if (startPage === 1) {
                    endPage = Math.min(totalPages, startPage + 4);
                } else {
                    startPage = Math.max(1, endPage - 4);
                }
            }

            // 第一页
            if (startPage > 1) {
                paginationHTML += `<button data-page="1" ${currentPage === 1 ? 'class="active"' : ''}>1</button>`;
                if (startPage > 2) {
                    paginationHTML += '<span style="padding: 8px;">...</span>';
                }
            }

            // 中间页码
            for (let i = startPage; i <= endPage; i++) {
                const activeClass = i === currentPage ? 'class="active"' : '';
                paginationHTML += `<button data-page="${i}" ${activeClass}>${i}</button>`;
            }

            // 最后一页
            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    paginationHTML += '<span style="padding: 8px;">...</span>';
                }
                paginationHTML += `<button data-page="${totalPages}" ${currentPage === totalPages ? 'class="active"' : ''}>${totalPages}</button>`;
            }

            // 下一页
            const nextDisabled = currentPage === totalPages ? 'disabled' : '';
            paginationHTML += `<button ${nextDisabled} data-page="${currentPage + 1}" title="下一页">
                <i class="fas fa-chevron-right"></i>
            </button>`;

            paginationHTML += `<div class="page-info">第 ${currentPage} 页，共 ${totalPages} 页 | 总计 ${totalItems} 条记录</div>`;
            paginationHTML += '</div>';

            return paginationHTML;
        }

        // 绑定分页事件
        function bindPaginationEvents(positionName, positionData) {
            const paginationButtons = document.querySelectorAll('.pagination button[data-page]');
            
            paginationButtons.forEach((button, index) => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    const page = parseInt(this.getAttribute('data-page'));
                    const totalPages = Math.ceil(positionData.data.length / itemsPerPage);
                    
                    if (page !== currentPage && page >= 1 && page <= totalPages && !this.disabled && !this.hasAttribute('disabled')) {
                        currentPage = page;
                        displayPositionData(positionName, positionData);
                    }
                });
            });
        }

        // 显示空内容
        function displayEmptyContent(positionName) {
            const contentArea = document.getElementById('data-content-area');
            contentArea.innerHTML = `
                <div class="card">
                    <div class="card-header">
                        <h2>${positionName} - 风险数据</h2>
                        <i class="fas fa-table"></i>
                    </div>
                    <div style="text-align: center; padding: 40px; color: #666;">
                        <i class="fas fa-inbox" style="font-size: 3rem; margin-bottom: 20px;"></i>
                        <p>暂无${positionName}的风险数据</p>
                        <p>请先导入Excel数据文件</p>
                    </div>
                </div>
            `;
        }

        // 加载示例数据
        function loadSampleData() {
            // 如果已经有数据，不加载示例数据
            const hasRiskData = Object.keys(riskData).some(pos => riskData[pos] && riskData[pos].data && riskData[pos].data.length > 0);
            const hasKeyRiskData = Object.keys(keyRisksData).length > 0;
            
            if (hasRiskData || hasKeyRiskData) {
                return;
            }

            // 如果没有数据，显示空状态
            displayEmptyContent('签派放行席');
            
            // 生成示例重点风险
            generateSampleRiskClouds();
        }

        // 生成示例重点风险显示
        function generateSampleRiskClouds() {
            const cloudContainer = document.getElementById('risk-cloud-container');
            const colorLevels = [
                'high-risk', 'medium-risk', 'low-risk', 'normal',
                'purple-risk', 'blue-risk', 'teal-risk', 'indigo-risk',
                'pink-risk', 'cyan-risk'
            ];
            
            const sampleKeyRisks = {
                '签派放行席': [
                    { content: '高原机场超轮速风险', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] },
                    { content: '新开航线性能限制', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] },
                    { content: '新放单人员资质管理', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] },
                    { content: '温度变化对性能影响', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] },
                    { content: '小风等恶劣天气应对', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] }
                ],
                '计划控制席': [
                    { content: '军事活动空域占用', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] },
                    { content: '信息系统中断风险', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] },
                    { content: '空域管制协调', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] },
                    { content: '断电断网应急处置', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] }
                ],
                '签派支援席': [
                    { content: '短跑道机场运行风险', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] },
                    { content: '航路禁航影响', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] },
                    { content: '天气标准变更', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] }
                ],
                '航班计划席': [
                    { content: 'T3CAS地形数据库缺失', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] },
                    { content: 'Honeywell数据库未更新', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] },
                    { content: '新建跑道数据同步', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] }
                ],
                '助理签派席': [
                    { content: '备份PAD电量不足', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] },
                    { content: 'EFB数据不一致', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] },
                    { content: '代理单位错误操作', level: colorLevels[Math.floor(Math.random() * colorLevels.length)] }
                ]
            };

            cloudContainer.innerHTML = '';
            Object.keys(positionMapping).forEach(positionName => {
                const positionKey = positionMapping[positionName];
                const risks = sampleKeyRisks[positionName] || [];

                const cloudDiv = document.createElement('div');
                cloudDiv.className = 'position-cloud';

                const icons = {
                    'dispatch': 'fas fa-paper-plane',
                    'plan-control': 'fas fa-clipboard-list',
                    'dispatch-support': 'fas fa-hands-helping',
                    'flight-plan': 'fas fa-route',
                    'assistant-dispatch': 'fas fa-user-friends'
                };

                cloudDiv.innerHTML = `
                    <h3><i class="${icons[positionKey]}"></i> ${positionName}</h3>
                    <div class="cloud-words">
                        ${risks.map(risk => 
                            `<span class="risk-word ${risk.level}" title="${risk.content}">${risk.content}</span>`
                        ).join('')}
                    </div>
                `;
                cloudContainer.appendChild(cloudDiv);
            });
        }

        // 初始化留言板
        function initMessageBoard() {
            const messageForm = document.getElementById('message-form');
            const messagesList = document.getElementById('messages-list');
            const emptyMessage = document.getElementById('empty-message');
            const downloadBtn = document.getElementById('download-messages');
            const clearBtn = document.getElementById('clear-messages');
            const passwordModal = document.getElementById('password-modal');
            const passwordInput = document.getElementById('password-input');
            const passwordConfirm = document.getElementById('password-confirm');

            // 从服务器加载留言
            let messages = [];
            
            async function loadMessages() {
                try {
                    messages = await loadMessagesFromServer();
                    displayMessages();
                } catch (error) {
                    console.error('加载留言失败:', error);
                    messages = [];
                    displayMessages();
                }
            }

            // 显示留言
            function displayMessages() {
                if (messages.length === 0) {
                    emptyMessage.style.display = 'block';
                    messagesList.innerHTML = '';
                    messagesList.appendChild(emptyMessage);
                    return;
                }

                emptyMessage.style.display = 'none';
                messagesList.innerHTML = '';

                // 按时间倒序显示留言
                messages.slice().reverse().forEach(msg => {
                    const messageItem = document.createElement('div');
                    messageItem.className = 'message-item';

                    const messageHeader = document.createElement('div');
                    messageHeader.className = 'message-header';

                    const authorSpan = document.createElement('span');
                    authorSpan.className = 'message-author';
                    authorSpan.textContent = `${msg.author} (${msg.position})`;

                    const dateSpan = document.createElement('span');
                    dateSpan.className = 'message-date';
                    dateSpan.textContent = new Date(msg.timestamp).toLocaleString();

                    messageHeader.appendChild(authorSpan);
                    messageHeader.appendChild(dateSpan);

                    const contentDiv = document.createElement('div');
                    contentDiv.className = 'message-content';
                    contentDiv.textContent = msg.content;

                    messageItem.appendChild(messageHeader);
                    messageItem.appendChild(contentDiv);

                    messagesList.appendChild(messageItem);
                });
            }

            // 提交留言
            messageForm.addEventListener('submit', async function (e) {
                e.preventDefault();

                const authorName = document.getElementById('author-name').value;
                const authorPosition = document.getElementById('author-position').value;
                const messageContent = document.getElementById('message-content').value;

                if (!authorName || !authorPosition || !messageContent) {
                    showNotification('请填写所有必填字段！', true);
                    return;
                }

                // 添加新留言
                const newMessage = {
                    author: authorName,
                    position: authorPosition,
                    content: messageContent,
                    timestamp: new Date().getTime()
                };

                try {
                    // 保存到服务器
                    await saveMessageToServer(newMessage);
                    messages.push(newMessage);
                    
                    // 清空表单
                    messageForm.reset();
                    
                    // 更新显示
                    displayMessages();
                    
                    showNotification('留言提交成功！');
                } catch (error) {
                    console.error('保存留言失败:', error);
                    showNotification('留言提交失败：' + error.message, true);
                }
            });

            // 下载留言
            downloadBtn.addEventListener('click', function () {
                if (messages.length === 0) {
                    showNotification('没有留言可下载！', true);
                    return;
                }

                let content = 'AOC航务席位岗位风险隐患清单 - 留言记录\n';
                content += '生成时间: ' + new Date().toLocaleString() + '\n';
                content += '==========================================\n\n';

                messages.forEach((msg, index) => {
                    content += `留言 ${index + 1}:\n`;
                    content += `填写人: ${msg.author} (${msg.position})\n`;
                    content += `时间: ${new Date(msg.timestamp).toLocaleString()}\n`;
                    content += `内容: ${msg.content}\n`;
                    content += '------------------------------------------\n';
                });

                const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
                const url = URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = `风险留言记录_${new Date().getTime()}.txt`;
                document.body.appendChild(a);
                a.click();

                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                }, 100);

                showNotification('留言下载成功！');
            });

            // 清零留言按钮点击事件
            clearBtn.addEventListener('click', function () {
                if (messages.length === 0) {
                    showNotification('没有留言可清空！', true);
                    return;
                }

                // 显示密码验证模态框
                passwordInput.value = '';
                passwordModal.style.display = 'flex';
            });

            // 密码确认按钮点击事件
            passwordConfirm.addEventListener('click', async function () {
                const password = passwordInput.value;

                if (password === '123456') {
                    try {
                        // 密码正确，清空留言
                        await clearMessagesOnServer();
                        messages = [];
                        displayMessages();
                        passwordModal.style.display = 'none';
                        showNotification('留言已清空！');
                    } catch (error) {
                        console.error('清空留言失败:', error);
                        showNotification('清空留言失败：' + error.message, true);
                    }
                } else {
                    // 密码错误
                    showNotification('密码错误，请重新输入！', true);
                    passwordInput.value = '';
                    passwordInput.focus();
                }
            });

            // 按Enter键确认密码
            passwordInput.addEventListener('keypress', function (e) {
                if (e.key === 'Enter') {
                    passwordConfirm.click();
                }
            });

            // 初始加载留言
            loadMessages();
            
            // 定时刷新留言（每30秒）
            setInterval(loadMessages, 30000);
        }

        // 显示通知
        function showNotification(message, isError = false) {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.className = isError ? 'notification error' : 'notification';
            notification.style.display = 'block';

            setTimeout(() => {
                notification.style.display = 'none';
            }, 3000);
        }
    </script>
</body>

</html>